#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

bool serialize(Json::Value &root, std::string &jsonStr)
{
    std::stringstream ss;
    Json::StreamWriterBuilder builter;
    std::unique_ptr<Json::StreamWriter> writer(builter.newStreamWriter());
    int ret = writer->write(root, &ss);
    if(ret)
    {
        std::cout << "serialize failed" << std::endl;
        return false;
    }
    jsonStr = ss.str();
    return true;
}

bool deserialize(std::string &jsonStr, Json::Value &root)
{
    Json::CharReaderBuilder builter;
    std::unique_ptr<Json::CharReader> reader(builter.newCharReader());
    std::string errs;
    int ret = reader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.size(), 
            &root, &errs);
    if(ret)
    {
        std::cout << "deserialize failed" << std::endl;
        return false;
    }
    return true;
}

int main()
{
    Json::Value root;
    root["name"] = "jsoncpp";
    root["age"] = 18;
    root["sex"] = "male";
    std::string jsonStr;
    serialize(root, jsonStr);
    std::cout << jsonStr << std::endl;

    Json::Value root2; 
    deserialize(jsonStr, root2);
    std::cout << root2["name"] << std::endl;
    std::cout << root2["age"] << std::endl;
    std::cout << root2["sex"] << std::endl;
    for(auto it = root2.begin(); it != root2.end(); ++it)
    {
        std::cout << it.key() << std::endl;
    }
    return 0;
}
